/**
 * Created by Administrator on 2017/12/27.
 * 菜单管理JS
 */
layui.config({
    base: '../build/js/'
}).use(['ztree', 'layer','table','form'], function() {
    var $ = layui.jquery,
        layer = layui.layer
        ,table = layui.table
        ,form = layui.form
        ,addMenuLayer=null;

    /**
     * 加载菜单树
     * @type {Array}
     */
    var zNodes = [];
    var loadMenusParam={systemId:"upms",pId:1,keyWord:"",level:0};
    var setting = {
        view: {
            addHoverDom: addHoverDom,
            selectedMulti: false
        },
        check: {
            enable: false
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        edit: {
            enable: false
        },
        callback: {
            onClick: zTreeOnClick
        }
    };


    $(document).ready(function() {
        //初始化树
        initZTree();
        //绑定Form表单监听事件
        form.on('submit(addMenuSubmit)', function(data) {
            var loadIndex = layer.load(2, {
                shade: [0.3, '#333']
            });
            data.field.isLeaf=1;
            data.field.pId=loadMenusParam.pId;
            data.field.systemId="upms";
            data.field.level=parseInt(loadMenusParam.level)+1;
            $.post("/sysMenu/addMenuNode", data.field, function(res) {
                loadIndex && layer.close(loadIndex);
               if(res.code==0){
                   layer.msg(res.msg, {
                       icon: 1,
                       time:3000
                   });
                   layer.close(addMenuLayer);
                   table.reload('menusTable', {
                       where: loadMenusParam
                   });
               }else{
                   layer.msg(res.msg, {
                       icon: 2,
                       time:3000
                   });
               }
            }, 'json');
        });
    });

    //初始化树
    function initZTree() {
        $.post("/sysMenu/menuTree", {systemId:"upms",state:0}, function(res) {
            if(res){
                zNodes=res;
                var zTreeObj =$.fn.zTree.init($("#ztree"), setting, zNodes);
                zTreeObj.expandAll(true);
            }
        }, 'json');
    }
    
    function addHoverDom(treeId, treeNode) {
        var sObj = $("#" + treeNode.tId + "_span");
        if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0)
            return;
        var addStr = "<span class='button add' id='addBtn_" + treeNode.tId +
            "' title='add node' onfocus='this.blur();'></span>";
        sObj.after(addStr);
        var btn = $("#addBtn_" + treeNode.tId);
        if (btn) {
            btn.bind("click", function() {
                var level=treeNode.level;
                if(level>0){
                    layer.msg("只能添加2级菜单！", {
                        icon: 2
                    })
                }else{
                    var zTree = $.fn.zTree.getZTreeObj("ztree");
                    level=level+1;
                    var newNode={name:"新菜单",pId:treeNode.id,systemId:"upms",isLeaf:0,level:level}
                    $.post("/sysMenu/addMenuNode",newNode, function(res) {
                        if(res){
                           if(res.code==0){
                               newNode.id=res.data.id;
                               zTree.addNodes(treeNode,newNode);
                               loadMenusParam.pId=treeNode.id;
                               table.reload('menusTable', {
                                   where: loadMenusParam
                               });
                           }else{
                               layer.msg(res.msg, {
                                   icon: 2
                               });
                           }
                        }
                    }, 'json');
                }
                return false;
            });
        }
    };

    function zTreeOnClick(event, treeId, treeNode) {
        loadMenusParam.pId=treeNode.id;
        loadMenusParam.level=treeNode.level;
        loadMenusParam.keyWord="";
        table.reload('menusTable', {
            where: loadMenusParam
        });
    };

    //加载子级菜单列表
    table.render({
        elem: '#menus'
        ,url:'../sysMenu/selectMenus'
        ,where:loadMenusParam
        ,method:'post'
        ,limit:15
        ,cellMinWidth: 80
        ,cols: [[
             {type: 'checkbox'}
            ,{field:'name', title:'名称',edit: 'text'}
            ,{field:'path', title:'链接',minWidth:120,edit: 'text'}
            ,{field:'icon', title: '图标',minWidth:120,edit: 'text',templet: '#showIconTpl'}
            ,{field:'permission', title: '权限',minWidth:120,edit: 'text'}
            ,{field:'type', title: '类型',minWidth:120,templet: '#showTypeTpl'}
            ,{field:'order', title: '排序',minWidth:40,edit: 'text'}
            ,{fixed: 'right', width:100, align:'center', toolbar: '#barMenus'}
        ]]
        ,id: 'menusTable'
    });

    //监听单元格编辑
    table.on('edit(menus)', function(obj){
        var value = obj.value //得到修改后的值
            ,data = obj.data //得到所在行所有键值
            ,field = obj.field; //得到字段
        data[field]=value;
        $.post("/sysMenu/updateMenu",data, function(res) {
            if(res){
                if(res.code==0){
                    initZTree();
                    table.reload('menusTable', {
                        where: loadMenusParam
                    });
                }else{
                    layer.msg(res.msg, {
                        icon: 2
                    });
                }
            }
        }, 'json');
    });

    //监听工具条
    table.on('tool(menus)', function(obj){
        var data = obj.data;
       if(obj.event === 'del'){
            layer.confirm('真的删除行么', function(index){
                $.post("/sysMenu/deleteMenu",{id:data.id}, function(res) {
                    if(res){
                        if(res.code==0){
                            layer.msg(res.msg, {
                                icon: 1,
                                time: 3000 //3s后自动关闭
                            });
                            table.reload('menusTable', {
                                where: loadMenusParam
                            });
                        }else{
                            layer.msg(res.msg, {
                                icon: 2
                            });
                        }
                    }
                }, 'json');
            });
        }
    });

    var active = {
        addMenu: function(){ //验证是否全选
            addMenuLayer=layer.open({
                type:1,
                area:'30%',
                offset:'20%',
                maxmin:true,
                skin:'layui-layer-molv',
                content:$("#addMenuForm")
            });
        }
    };

    $('.menusToolBar .layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
});
